# -*- coding: utf-8 -*-
class ClaimController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter ,:except=>[:claimList,:newClaimFromEntry,:editClaimFromEntry]

  def claimList
    
  end

  def transformEntryIntoClaim
    paramsHash = Util.paramsPreprocesseToHash(params[:data])

    warehousingEntryId = paramsHash['warehousing_entry_id']
    warehouseId = paramsHash['warehouse_id']

    warehousingEntry =  WarehousingEntry.find(warehousingEntryId)
    if warehousingEntry.deal_with_status == Constants::CANCELED
      info = "已经撤消的入库单，不可以再进行索赔处理！"
    else
      claim = Claim.new
      claim.purchase_order_id = warehousingEntry.id
      claim.company_id = warehousingEntry.company_id
      claim.department_id = warehousingEntry.department_id
      claim.employee_id = warehousingEntry.employee_id
      claim.action_date = paramsHash['action_date']
      claim.warehousing_entry_id = warehousingEntry.id
      claim.purchase_order_id = warehousingEntry.purchase_order_id
      claim.warehouse_id = warehouseId
      claim.logistics_id = paramsHash['logistics_id']
      claim.linkman = paramsHash['linkman']
      claim.phone = paramsHash['phone']
      claim.auditing_status = Constants::PASS_APPLY_ADD
      claim.save!  #先行保存一下，以便生成ID
      
      #为了在进行结算表操作时提前获取ID，这时要提前存储warehousingEntry


      #向详细表中插入products信息
      productsHashArray = paramsHash["products"]
      productsHashArray.each do |productHash|
        #如果不为空则加入
        if productHash["product_id"] !=""
          #得到采购订单的详细价格，只有取出它的详细记录来。
          warehousingEntryDetail = WarehousingEntryDetail.find(productHash["id"])
          claimDetail = ClaimDetail.new
          claimDetail.purchase_order_id = warehousingEntry.purchase_order_id
          claimDetail.warehousing_entry_id = warehousingEntry.id
          claimDetail.product_id = productHash["product_id"]
          claimDetail.quantity = productHash["quantity"]
          claimDetail.unit_price = warehousingEntryDetail.unit_price
          claimDetail.amount = claimDetail.quantity * claimDetail.unit_price
          claim.amount = claim.amount + claimDetail.amount          #计算订单总金额
          claimDetail.description = productHash["description"]
          claim.claim_details << claimDetail
          claim.save!
          
          #同时生成结算表的内容。
          productCollection = ProductCollection.new
          #copy内容到结算表
          #在进行成功转换后，要同时操作结算表，把此次操作的详细内容，完全拆解开，复制到结算表中。
          productCollection.company_id = claim.company_id
          productCollection.department_id = claim.department_id
          productCollection.employee_id = claim.employee_id
          productCollection.logistics_id = claim.logistics_id
          productCollection.amount = 0 - claim.amount
          productCollection.warehouse_id = warehouseId
          productCollection.product_id = claimDetail.product_id
          productCollection.quantity = 0 - claimDetail.quantity  #warehousingEntryDetail.quantity
          productCollection.unit_price = claimDetail.unit_price
          productCollection.unit_amount = 0 - claimDetail.amount
          productCollection.resource_id =  claim.id
          productCollection.resource_type =  Claim.name
          productCollection.description =  claimDetail.description
          productCollection.action_date = claim.action_date
          productCollection.purchase_order_id =  claimDetail.purchase_order_id
          productCollection.warehousing_entry_id =  claimDetail.warehousing_entry_id
          productCollection.save!
        end
      end

      #开始事务，确保在流水号正常的情况下，保存入库单时,一但出现问题，则循环执行
      begin
        Sequence.transaction do
          #开始为出库单取得流水号
          sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],Claim.name])

          sequence.seq_no = sequence.seq_no + 1
          claim.seq_number = sequence.seq_no
          claim.order_number = sequence.ab + ":" + claim.seq_number.to_s + ":" + Date.today.to_s
          sequence.save!
          claim.save!
        end
      rescue ActiveRecord::StaleObjectError
        #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
        #这里特别指序号产生表。
        logger.info "somebody useing sn before yours.............................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
        retry
      rescue ActiveRecord::RecordNotFound
        logger.info "RecordNotFound................................................................................"
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
      rescue Exception => e
        logger.info "logging......................................................................................."
        DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
        logger.info e
      end
      info = "成功"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #在编辑时得到可以编辑的详细的索赔信息
  def getDetailsBalanceByIdForEdit
    claimId = params[:claim_id]
    claim = Claim.find(claimId)
    #销售详细
    #balance_quantity为当前最大的可入数量。即修改后的数字不能大于balance_quantity
    claimDetails = ClaimDetail.find(:all,:select=>"cd.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,cd.quantity,ed.amount,cd.description,newcd.quantity as cd_quantity,(ed.quantity - ifnull(newcd.quantity,0) + cd.quantity) as balance_quantity",:joins =>"cd
left join (select product_id,sum(quantity) as quantity
from claim_details cd left join claims c on cd.claim_id = c.id
where c.id = #{claim.id} AND c.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by cd.product_id) newcd on newcd.product_id = cd.product_id
left join products p on p.id = cd.product_id
left join warehousing_entry_details ed on ed.warehousing_entry_id = cd.warehousing_entry_id and cd.product_id = ed.product_id AND ed.is_locked = 0
where cd.claim_id =  "+claimId)

    jsonStr="{totalProperty:"+claimDetails.length.to_s+",root:"+claimDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  
  def update
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]
    claim = Claim.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND (auditing_status is null OR auditing_status not like ?)",paramsHash['id'],session[:company_id],'%撤消%'])
    if claim != nil
      claim.company_id = session[:company_id]
      claim.department_id = session[:department_id]
      claim.employee_id = session[:employee_id]
      claim.warehouse_id = paramsHash['warehouse_id']
      claim.action_date = paramsHash['action_date']
      claim.description = paramsHash['description']

      claim.audit_opinion = ''
      claim.auditor_id = session[:employee_id]

      claim.auditing_status = Constants::PASS_APPLY_EDIT

      #products信息
      productsHashArray = paramsHash["products"]
      #在这里，要作一个增，删，编辑操作，以前台数据为准。
      #首先各取出前台与后台的ID数组
      fgIdArray = Array.new
      productsHashArray.each do |productHash|
        fgIdArray << productHash["id"].to_i
      end

      bgIdArray = Array.new
      claimDetails = claim.claim_details
      claimDetails.each do |claimDetail|
        bgIdArray << claimDetail.id
      end

      idIntersectionArray = fgIdArray & bgIdArray
      addIdArray = fgIdArray - idIntersectionArray
      delIdArray = bgIdArray - idIntersectionArray
      #得到要删除的产品Id数组

      if !delIdArray.empty?
        claimDetails = ClaimDetail.find(:all,:conditions=>["id in (?)",delIdArray])
        productIdArray = Array.new
        claimDetails.each do |claimDetail|
          productIdArray << claimDetail.product_id
        end       
        
        ClaimDetail.delete(delIdArray)
        #删除汇总表中的相关内容
        ProductCollection.delete_all(["resource_type = 'Claim' AND product_id in (?) AND resource_id = ?",productIdArray,claim.id])
      end

      #在进行从新整理数据之前，先把销售订单的总金额置“0”
      claim.amount = 0

      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          #没Id说明是新增加的。
          if productHash["id"] != ""
            claimDetail = ClaimDetail.find(productHash["id"].to_i)
            claimDetail.quantity = productHash["quantity"] #对于出入库来说其实只有数量为唯一的考量。
            claimDetail.description = productHash["description"]
            claimDetail.save
            #同时把汇总表中的相关记录进行修改
            ProductCollection.update_all("warehouse_id = #{claim.warehouse_id},quantity = #{claimDetail.quantity}","resource_type = 'Claim' AND resource_id = #{claim.id} AND product_id = #{claimDetail.product_id} AND warehousing_entry_id = #{claimDetail.warehousing_entry_id} AND is_locked = 0 AND product_id =#{claimDetail.product_id}")
          end
        end
      end
      claim.save
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getAllClaims
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i

      conditionsStr = ''

      if params[:order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number in (:order_number)'
        else
          conditionsStr = conditionsStr+' AND seq_number in (:order_number)'
        end
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status like :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
        end
        conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
      elsif params[:auditing_status] == ' '
        if conditionsStr == ''
          conditionsStr = 'auditing_status = :auditing_status'
        else
          conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
        end
        conditionsHash[:auditing_status] = ''
      end

      if params[:customer_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'customer_id = :customer_id'
        else
          conditionsStr = conditionsStr+' AND customer_id = :customer_id'
        end
        conditionsHash[:customer_id] = params[:customer_id].to_i
      end

      #销售员
      if params[:sales_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sales_id = :sales_id'
        else
          conditionsStr = conditionsStr+' AND sales_id = :sales_id'
        end
        conditionsHash[:sales_id] = params[:sales_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      #显示产品
      if params[:product_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'sale_order_details.product_id = :product_id'
        else
          conditionsStr = conditionsStr+' AND sale_order_details.product_id = :product_id'
        end
        conditionsHash[:product_id] = params[:product_id].to_i
      end

      #显示产品
      if params[:department_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'department_id = :department_id'
        else
          conditionsStr = conditionsStr+' AND department_id = :department_id'
        end
        conditionsHash[:department_id] = params[:department_id].to_i
      end

      count = Claim.countAllClaims conditionsStr,conditionsHash
      claims = Claim.findAllClaims conditionsStr,conditionsHash,paramsHash

      jsonStr="{totalProperty:"+count.to_s+",root:"+claims.to_json(:include=>[:logistics,:purchase_order,:warehousing_entry,:department,:employee])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  def getClaimById
    claim = Claim.find(params[:id])
    rootStr = claim.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到某索赔的详细信息
  def getClaimDetailsById
    
  end

  #查看索赔订单的详细信息，并显示索赔与返库差比
  def getClaimDetailsBalanceById
    claimId = params[:claim_id]
    claimDetails = ClaimDetail.find(:all,:select=>"cd.id,cd.quantity as quantity,cd.unit_price,cd.amount,p.name as product_name,p.is_suit,p.number as product_number,p.spec,p.unit,newrd.quantity as rd_quantity,(ifnull(newrd.quantity,0)-cd.quantity) as balance_quantity",:joins =>"cd
left join (select crd.product_id,sum(crd.quantity) as quantity
from claim_details cd left join claim_returneds cr on cd.id = cr.claim_id
left join claim_returned_details crd on crd.claim_returned_id = cr.id
where cd.claim_id = "+claimId+" AND cr.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by crd.product_id) newrd on newrd.product_id = cd.product_id
left join products p on p.id = cd.product_id
where cd.claim_id =  " + claimId)
    jsonStr="{totalProperty:"+claimDetails.length.to_s+",root:"+claimDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
  


  #得到可供入库的详细货品种类与数量，已经入过的会排除在外。这次要针对product_id分组，因为在采购订单中是由销售订单和产品二个参数分组的。
  #此版本的修改是为了显示每个采购订单中的不同的销售订单的单号。不再以产品Id为唯一区分。
  def getDetailBalanceForReturned
    claimId = params[:claim_id]
    claimDetails = ClaimDetail.find(:all,:select=>"cd.id,p.id as product_id,p.name as product_name,p.is_suit,p.unit_price,p.number,p.spec,p.unit,cd.quantity,cd.description,newrd.quantity as rd_quantity,(sum(cd.quantity) - ifnull(newrd.quantity,0)) as balance_quantity",:joins =>"cd
left join (select product_id,sum(quantity) as quantity from claim_returned_details crd left join claim_returneds cr on crd.claim_returned_id = cr.id
where cr.claim_id = "+claimId+" AND cr.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newrd on newrd.product_id = cd.product_id
left join products p on p.id = cd.product_id
where cd.claim_id =  "+claimId+ " group by cd.product_id having sum(cd.quantity) - ifnull(newrd.quantity,0) > 0")

    jsonStr="{totalProperty:"+claimDetails.length.to_s+",root:"+claimDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #申请撤消
  def applyToCancel
    begin
      claim = Claim.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_claim_cancel == "否"
        claim.auditing_status = Constants::PASS_APPLY_CANCEL
        claim.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'Claim' AND resource_id = #{params[:id]}")
        #如果不需要审核，则把汇总表中的数据设置为is_locked = 1
      else
        claim.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      claim.auditor_id = session[:employee_id]
      claim.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
end
